package com.dao;

import java.sql.Timestamp;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

import com.base.BaseDao;
import com.base.PageBean;
import com.base.UserBean;
import com.bean.ParkManager;
import com.bean.ParkOrder;
import com.bean.Parkinfo;
import com.bean.PerformanceBean;
import com.bean.UserCreditRecord;
import com.bean.Userinfo;
import com.util.GUtil;

/**
 * A data access object (DAO) providing persistence and search support for
 * ParkOrder entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.bean.ParkOrder
 * @author MyEclipse Persistence Tools
 */
public class ParkOrderDao extends BaseDao {
	private static final Logger log = Logger.getLogger(ParkOrderDao.class);
	// property constants
	public static final String PO_NO = "poNo";
	public static final String PO_TYPE = "poType";
	public static final String CAR_NO = "carNo";
	public static final String CAR_COLOR = "carColor";
	public static final String CAR_BRAND = "carBrand";
	public static final String ENTER_IMG = "enterImg";
	public static final String LEAVE_IMG = "leaveImg";
	public static final String RESERVATION_DURATION = "reservationDuration";
	public static final String ACTUAL_DURATION = "actualDuration";
	public static final String RESERVATION_AMOUNT = "reservationAmount";
	public static final String RECEIVABLE_AMOUNT = "receivableAmount";
	public static final String ACTUAL_AMOUNT = "actualAmount";
	public static final String DIFF_AMOUNT = "diffAmount";
	public static final String PARK_PRICE = "parkPrice";
	public static final String CHANGE_AMOUNT_REASON = "changeAmountReason";
	public static final String CARPORT_COUNT = "carportCount";
	public static final String COMMENT_STATUS = "commentStatus";
	public static final String REPORT_STATUS = "reportStatus";
	public static final String STATUS = "status";
	
	/**
	 * 绩效统计
	 * <p>Title: statisMyParkPerformance</p>
	 * <p>Description: 
	 * 		统计某月的收费员的绩效考核信息
	 * </p>
	 * @param pm	停车场超级管理员
	 * @param parkInfo	查询条件，停车场id（可选）
	 * @param dateTime  查询条件，月份（必选）
	 * @param page		分页
	 * @return
	 * @throws Exception
	 */
	public List<PerformanceBean> statisMyParkPerformance(List<Parkinfo> listPark, ParkManager pm, Parkinfo parkInfo, String dateTime, PageBean page) throws Exception{
		session = this.getSession();
		if(listPark==null )
			throw new Exception("listPark cannot be null");
		if(listPark.size()<1)
			return null;
		String ids = "";
		for(int i=0; i < listPark.size(); i++){
			if(i>0)
				ids += ",";
			ids += listPark.get(i).getPId();
		}
		String hql = "select new com.bean.PerformanceBean(po.parkManagerByLeaveOperatorId.userId," +
								" (select pm.userName from ParkManager pm where pm.userId=po.parkManagerByLeaveOperatorId.userId)," +
								" (select pm.realName from ParkManager pm where pm.userId=po.parkManagerByLeaveOperatorId.userId), " +
								" count(poId), sum(po.receivableAmount), sum(po.actualAmount))" +
								" from  ParkOrder po where status=20 "+
								" and po.leaveTime like '"+dateTime+"%' ";
		if(pm!=null){
			if(pm.getUserName()!=null && !pm.getUserName().trim().isEmpty())
				hql += " and po.parkManagerByLeaveOperatorId.userName like '%"+pm.getUserName().trim()+"%' ";
			if(pm.getRealName()!=null && !pm.getRealName().trim().isEmpty())
				hql += " and po.parkManagerByLeaveOperatorId.realName like '%"+pm.getRealName().trim()+"%' ";
		}
		if(parkInfo!=null){
			if(parkInfo.getPId()!=null && parkInfo.getPId()>0)
				hql += " and parkinfo.PId="+parkInfo.getPId();
			else
				hql += "and parkinfo.PId in("+ids+") ";
		}else
			hql += "and parkinfo.PId in("+ids+") ";
		
		String group = " group by po.parkManagerByLeaveOperatorId.userId";
		Query query = session.createQuery(hql+group);
		List<PerformanceBean> list = query.list();
		return list;
	}
	/*
	 * 分页
	 */
	public List<ParkOrder> findList(String hql, Object prop) {
		List res = null;
		log.debug("finding all ParkOrder instances");
		try {
			Query query = session.createQuery(hql);
			query.setMaxResults(5);
			if (prop != null) {
				query.setProperties(prop);
			}
			res = query.list();
		} catch (Exception e) {
			log.error("find all failed", e);
			e.printStackTrace();
		}
		return res;
	}
	// 停车场管理员查询本停车场的所有订单
	public List<ParkOrder> queryMyParkOrder(ParkOrder object, UserBean userBean,PageBean page) {
		session = getSession();
		log.debug("finding all ParkOrder instances");
		StringBuffer sb = new StringBuffer();
		try {
			sb.append("from ParkOrder where parkinfo.PId in( select PId from ParkinfoManagerRelevance where userId=?) and "
					+ " ((poType=1 and status in(1,2,3)) or (poType=2 and status =2)) ");
			ParkManager pm = (ParkManager) session.get(ParkManager.class,
					userBean.getId());
			if (pm == null)
				return null;
			// 获取我的停车场，通过Parkinfo中的属性parkOrders的集合就是自己的停车场
			// String queryString =
			// "from Parkinfo p where p.PId in( select PId from ParkinfoManagerRelevance where userId=?)";
			// String queryString =
			// "select p from Parkinfo p inner join p.parkManagers pm where pm.userId=?";
			// String queryString2 =
			// "from ParkOrder where parkinfo.PId in( select PId from ParkinfoManagerRelevance where userId=?)";

			if (object != null && !"".equals(object)) {
				// 订单类型
				if (object.getStatus() != null
						&& !"".equals(object.getStatus())) {
					Short s = object.getStatus();
					sb.append(" and status ='" + s + "'");
				}
				// 车场
				if (object.getParkinfo() != null) {
					Integer Pid = object.getParkinfo().getPId();
					if (object.getParkinfo().getPId() != null
							&& !"".equals(object.getParkinfo().getPId())) {
						sb.append(" and parkinfo.PId='" + Pid + "'");
					}
				}
				// 订单时间
				if (object.getOrderTime() != null
						&& !"".equals(object.getOrderTime())) {
					Timestamp t = object.getOrderTime();
					sb.append(" and orderTime like '" + t + "%'");
				}
				// 订单号
				if (object.getPoNo() != null && !"".equals(object.getPoNo())) {
					sb.append(" and poNo like '%" + object.getPoNo() + "%'");
				}
				// 车牌号
				if (object.getCarNo() != null && !"".equals(object.getCarNo())) {
					sb.append(" and carNo like '%" + object.getCarNo() + "%'");
				}
				// 用户名
				if (object.getUserinfo() != null) {
					if (object.getUserinfo().getRealName() != null
							&& !"".equals(object.getUserinfo().getRealName())) {
						sb.append(" and userinfo.realName like '%"
								+ object.getUserinfo().getRealName() + "%'");
					}
				}
			}
			sb.append(" order by poId asc");
			Long count = (Long) session.createQuery("select count(*) "+ sb.toString()).setLong(0, pm.getUserId()).uniqueResult();
			
			if(page!=null && count!=null )
				page.setTotalRow(count.intValue());
				Query queryObject = session.createQuery(sb.toString());
				queryObject.setLong(0,pm.getUserId());
			if(page!=null && page.getPageSize()>0 && page.getCurrentPage()>0){
					queryObject.setFirstResult( (page.getCurrentPage()-1)*page.getPageSize());
					queryObject.setMaxResults( page.getPageSize() );
				}
				
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	// 订单管理的query，-3：超时未支付的订单；-2：超时未确认定的订单；-1：管理员确认无法预订；0：订单已取消
	public List<ParkOrder> queryParkOrder(ParkOrder object, UserBean userBean,PageBean page) {
		session = getSession();
		log.debug("finding all ParkOrder instances");
		StringBuffer sb = new StringBuffer();
		try {
			session = this.getSession();
			ParkManager pm = (ParkManager) session.get(ParkManager.class,
					userBean.getId());
			if (pm == null)
				return null;
			sb.append("from ParkOrder where parkinfo.PId in( select PId from ParkinfoManagerRelevance where userId=?) and"
					+ "  ((status in(1,2,3,0,-1)))");
			if (object != null && !"".equals(object)) {
				// 订单类型
				if (object.getStatus() != null
						&& !"".equals(object.getStatus())) {
					Short s = object.getStatus();
					sb.append(" and status ='" + s + "'");
				}
				// 车场
				if (object.getParkinfo() != null) {
					Integer Pid = object.getParkinfo().getPId();
					if (object.getParkinfo().getPId() != null
							&& !"".equals(object.getParkinfo().getPId())) {
						sb.append(" and parkinfo.PId='" + Pid + "'");
					}
				}
				// 订单时间
				if (object.getOrderTime() != null
						&& !"".equals(object.getOrderTime())) {
					Timestamp t = object.getOrderTime();
					sb.append(" and orderTime like '" + t + "%'");
				}
				// 订单号
				if (object.getPoNo() != null && !"".equals(object.getPoNo())) {
					sb.append(" and poNo like '%" + object.getPoNo() + "%'");
				}
				// 车牌号
				if (object.getCarNo() != null && !"".equals(object.getCarNo())) {
					sb.append(" and carNo like '%" + object.getCarNo() + "%'");
				}
				// 用户名
				if (object.getUserinfo() != null) {
					if (object.getUserinfo().getRealName() != null
							&& !"".equals(object.getUserinfo().getRealName())) {
						sb.append(" and userinfo.realName like '%"
								+ object.getUserinfo().getRealName() + "%'");
					}
				}
			}

			sb.append("order by poId asc");
			Long count = (Long) session.createQuery("select count(*) "+ sb.toString()).setLong(0, pm.getUserId()).uniqueResult();
			
			if(page!=null && count!=null )
				page.setTotalRow(count.intValue());
				Query query = session.createQuery(sb.toString());
				query.setLong(0,pm.getUserId());
			if(page!=null && page.getPageSize()>0 && page.getCurrentPage()>0){
					query.setFirstResult( (page.getCurrentPage()-1)*page.getPageSize());
					query.setMaxResults( page.getPageSize() );
				}
			return query.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	// 收费员查询自己的订单
	public List<ParkOrder> queryMyOrder(ParkOrder object, UserBean userBean,PageBean page) {
		session = getSession();
		log.debug("finding all ParkOrder instances");
		StringBuffer sb = new StringBuffer();
		ParkManager pm = (ParkManager) session.get(ParkManager.class,
				userBean.getId());
		try {
			sb.append("from ParkOrder where 1=1");
			if (object != null && !"".equals(object)) {
				// 订单类型
				if (object.getStatus() != null
						&& !"".equals(object.getStatus())) {
					Short s = object.getStatus();
					sb.append(" and status ='" + s + "'");
				}
				// 车场
				if (object.getParkinfo() != null) {
					Integer Pid = object.getParkinfo().getPId();
					if (object.getParkinfo().getPId() != null
							&& !"".equals(object.getParkinfo().getPId())) {
						sb.append(" and parkinfo.PId='" + Pid + "'");
					}
				}
				// 订单时间
				if (object.getOrderTime() != null
						&& !"".equals(object.getOrderTime())) {
					Timestamp t = object.getOrderTime();
					sb.append(" and orderTime like '" + t + "%'");
				}
				// 订单号
				if (object.getPoNo() != null && !"".equals(object.getPoNo())) {
					sb.append(" and poNo like '%" + object.getPoNo() + "%'");
				}
				// 车牌号
				if (object.getCarNo() != null && !"".equals(object.getCarNo())) {
					sb.append(" and carNo like '%" + object.getCarNo() + "%'");
				}
				// 用户名
				if (object.getUserinfo() != null) {
					if (object.getUserinfo().getRealName() != null
							&& !"".equals(object.getUserinfo().getRealName())) {
						sb.append(" and userinfo.realName like '%"
								+ object.getUserinfo().getRealName() + "%'");
					}
				}
			}
			sb.append("order by poId asc");
			Long count = (Long) session.createQuery("select count(*) "+ sb.toString()).setLong(0, pm.getUserId()).uniqueResult();
			
			if(page!=null && count!=null )
				page.setTotalRow(count.intValue());
				Query queryObject = session.createQuery(sb.toString());
				queryObject.setLong(0,pm.getUserId());
			if(page!=null && page.getPageSize()>0 && page.getCurrentPage()>0){
					queryObject.setFirstResult( (page.getCurrentPage()-1)*page.getPageSize());
					queryObject.setMaxResults( page.getPageSize() );
				}
				
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List getAll(ParkOrder object) {
		session = getSession();
		log.debug("finding all ParkOrder instances");
		StringBuffer sb = new StringBuffer();
		try {
			sb.append("from ParkOrder where 1=1");
			if (object != null && !"".equals(object)) {
				// 订单类型
				if (object.getStatus() != null
						&& !"".equals(object.getStatus())) {
					Short s = object.getStatus();
					sb.append(" and status ='" + s + "'");
				}
				// 车场
				if (object.getParkinfo() != null) {
					Integer Pid = object.getParkinfo().getPId();
					if (object.getParkinfo().getPId() != null
							&& !"".equals(object.getParkinfo().getPId())) {
						sb.append(" and parkinfo.PId='" + Pid + "'");
					}
				}
				// 订单时间
				if (object.getOrderTime() != null
						&& !"".equals(object.getOrderTime())) {
					Timestamp t = object.getOrderTime();
					sb.append(" and orderTime like '" + t + "%'");
				}
				// 订单号
				if (object.getPoNo() != null && !"".equals(object.getPoNo())) {
					sb.append(" and poNo like '%" + object.getPoNo() + "%'");
				}
				// 车牌号
				if (object.getCarNo() != null && !"".equals(object.getCarNo())) {
					sb.append(" and carNo like '%" + object.getCarNo() + "%'");
				}
				// 用户名
				if (object.getUserinfo() != null) {
					if (object.getUserinfo().getRealName() != null
							&& !"".equals(object.getUserinfo().getRealName())) {
						sb.append(" and userinfo.realName like '%"
								+ object.getUserinfo().getRealName() + "%'");
					}
				}
			}
			sb.append("order by poId asc");

			Query queryObject = session.createQuery(sb.toString());
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List findAll(PageBean page) {
		session = getSession();
		log.debug("finding all ParkOrder instances");
		StringBuffer sb = new StringBuffer();
		try {
			sb.append("from ParkOrder");
			Long count = (Long) session.createQuery("select count(*) "+ sb.toString()).uniqueResult();
			if(page!=null && count!=null )
				page.setTotalRow(count.intValue());
				Query queryObject = session.createQuery(sb.toString());
			if(page!=null && page.getPageSize()>0 && page.getCurrentPage()>0){
					queryObject.setFirstResult( (page.getCurrentPage()-1)*page.getPageSize());
					queryObject.setMaxResults( page.getPageSize() );
				}
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List<ParkOrder> getOrderList(Long id) {
		log.debug("finding all ParkOrder instances");
		try {
			String queryString = "from ParkOrder where reservation_operator_id=?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setLong(0, id);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			System.out.println(re.getStackTrace());
			throw re;
		}
	}

	/*
	 * 删除
	 */
	public void delete(ParkOrder order) {
		log.debug("deleting ParkOrder instance");
		try {
			getSession().delete(order);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ParkOrder findById(Long id) {
		log.debug("getting ParkOrder instance with id: " + id);
		try {
			ParkOrder instance = (ParkOrder) getSession().get(ParkOrder.class,
					id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public ParkOrder findByuserinfoId(Long id) {
		log.debug("getting Userinfo instance with id: " + id);
		try {
			ParkOrder instance = (ParkOrder) getSession().get(Userinfo.class,
					id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public String delete(Long id, Integer flag) {
		ParkOrder po = this.findById(id);
		if (po != null) {
			return delete(po, flag);
		} else {
			return GUtil.FAILE;
		}
	}

	public String delete(ParkOrder order, Integer flag) {
		log.debug("deleting ParkOrder instance");
		try {
			if (flag == null)
				getSession().delete(order);
			else {
				order.setStatus(flag.shortValue());
				getSession().update(order);
			}
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public ParkOrder findByOrId(Long id) {
		log.debug("getting ParkOrder instance with id: " + id);
		try {
			ParkOrder instance = (ParkOrder) getSession().get(ParkOrder.class,
					id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(ParkOrder instance) {
		log.debug("finding ParkOrder instance by example");
		try {
			List results = getSession().createCriteria("com.dao.ParkOrder")
					.add(Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ParkOrder instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from ParkOrder as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByPoNo(Object poNo) {
		return findByProperty(PO_NO, poNo);
	}

	public List findByPoType(Object poType) {
		return findByProperty(PO_TYPE, poType);
	}

	public List findByCarNo(Object carNo) {
		return findByProperty(CAR_NO, carNo);
	}

	public List findByCarColor(Object carColor) {
		return findByProperty(CAR_COLOR, carColor);
	}

	public List findByCarBrand(Object carBrand) {
		return findByProperty(CAR_BRAND, carBrand);
	}

	public List findByEnterImg(Object enterImg) {
		return findByProperty(ENTER_IMG, enterImg);
	}

	public List findByLeaveImg(Object leaveImg) {
		return findByProperty(LEAVE_IMG, leaveImg);
	}

	public List findByReservationDuration(Object reservationDuration) {
		return findByProperty(RESERVATION_DURATION, reservationDuration);
	}

	public List findByActualDuration(Object actualDuration) {
		return findByProperty(ACTUAL_DURATION, actualDuration);
	}

	public List findByReservationAmount(Object reservationAmount) {
		return findByProperty(RESERVATION_AMOUNT, reservationAmount);
	}

	public List findByReceivableAmount(Object receivableAmount) {
		return findByProperty(RECEIVABLE_AMOUNT, receivableAmount);
	}

	public List findByActualAmount(Object actualAmount) {
		return findByProperty(ACTUAL_AMOUNT, actualAmount);
	}

	public List findByDiffAmount(Object diffAmount) {
		return findByProperty(DIFF_AMOUNT, diffAmount);
	}

	public List findByParkPrice(Object parkPrice) {
		return findByProperty(PARK_PRICE, parkPrice);
	}

	public List findByChangeAmountReason(Object changeAmountReason) {
		return findByProperty(CHANGE_AMOUNT_REASON, changeAmountReason);
	}

	public List findByCarportCount(Object carportCount) {
		return findByProperty(CARPORT_COUNT, carportCount);
	}

	public List findByCommentStatus(Object commentStatus) {
		return findByProperty(COMMENT_STATUS, commentStatus);
	}

	public List findByReportStatus(Object reportStatus) {
		return findByProperty(REPORT_STATUS, reportStatus);
	}

	public List findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	public List<ParkOrder> findparkname(UserBean userBean) {
		log.debug("finding all ParkOrder instances   ");
		session=getSession();
		ParkManager pm = (ParkManager) session.get(ParkManager.class,
				userBean.getId());
		try {
			String queryString = "select  p_id,p_name from parkinfo where p_id in(SELECT p_id from parkinfo_manager_relevance WHERE user_id=?)  GROUP BY p_name";
			Query queryObject = session.createSQLQuery(queryString);
			queryObject.setLong(0, pm.getUserId());
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ParkOrder merge(ParkOrder detachedInstance) {
		log.debug("merging ParkOrder instance");
		try {
			ParkOrder result = (ParkOrder) getSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public String update(ParkOrder order) {
		log.debug("merging ParkOrder instance");
		try {
			getSession().update(order);
			log.debug("merge successful");
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public String updateuserrecord(UserCreditRecord record) {
		log.debug("merging ParkOrder instance");
		try {
			getSession().save(record);
			log.debug("merge successful");
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public String updateuserinfo(Userinfo user) {
		log.debug("merging ParkOrder instance");
		try {
			getSession().update(user);
			log.debug("merge successful");
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public void attachDirty(ParkOrder instance) {
		log.debug("attaching dirty ParkOrder instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ParkOrder instance) {
		log.debug("attaching clean ParkOrder instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/*
	 * 绩效统计 "SELECT SUM(actualAmount),p.realName,pi.PName," +
	 * "COUNT(po.parkManagerByLeaveOperatorId.userId),COUNT(po.parkManagerByReservationOperatorId.userId)"
	 * +,count(distinct DATE_FORMAT((po.leaveTime),'%Y-%m-%d'))
	 */
	public List<ParkOrder> statistics(ParkOrder parkOrder,UserBean userBean,String datetime) {

		session = getSession();
		log.debug("finding all ParkOrder instances");
		StringBuffer sb = new StringBuffer();
		ParkManager pm = (ParkManager) session.get(ParkManager.class,
				userBean.getId());
		//String sql="select COUNT(distinct (DATE_FORMAT(p.leave_time,'%Y-%m-%d'))),pa.p_name,sum(p.actual_amount),pr.real_name,count(p.reservation_operator_id),count(p.leave_operator_id)from park_order p,parkinfo pa,park_manager pr,userinfo uwhere  u.user_id=p.order_user_id and p.p_id=pa.p_id and pr.user_id=p.order_user_id  and pa.p_id in( select p_id from parkinfo_manager_relevance where user_id=?)GROUP BY pa.p_name";
		try {
			sb.append("select pr.real_name,pa.p_name,sum(p.actual_amount),count(p.reservation_operator_id),"
					+ "count(p.leave_operator_id),COUNT(distinct (DATE_FORMAT(p.leave_time,'%Y-%m-%d')))"
					+ " from park_order p,parkinfo pa,park_manager pr,userinfo u where 1=1");
			if (parkOrder != null) {
				// 收费员
				if (parkOrder.getParkManagerByLeaveOperatorId() != null) {
					if (parkOrder.getParkManagerByLeaveOperatorId().getRealName() != null&& !"".equals(parkOrder.getParkManagerByLeaveOperatorId().getRealName())) {
						sb.append(" and pr.real_name like '%"+ parkOrder.getParkManagerByLeaveOperatorId().getRealName() + "%'");
					}
				}
				// 停车场
				if (parkOrder.getParkinfo() != null) {
					if (parkOrder.getParkinfo().getPId() != null && !"".equals(parkOrder.getParkinfo().getPId())) {
						sb.append(" and pa.p_id = '"+ parkOrder.getParkinfo().getPId() + "'");
					}
				}
				// try {
				// 月份
				// SimpleDateFormat dft = new SimpleDateFormat();
				// String d=parkOrder.getLeaveTime().toString();
				// System.out.println(d+"--------------------------------------------");
				if (datetime!= null&& !"".equals(datetime)) {
					sb.append(" and p.leave_time like '" + datetime + "%'");
				}
				// } catch (ParseException e) {
				// e.getStackTrace();
				// }
			}
			sb.append(" and u.user_id=p.order_user_id and p.p_id=pa.p_id and pr.user_id=p.order_user_id and pa.p_id in( select p_id from parkinfo_manager_relevance where user_id=?)" +
					" GROUP BY pa.p_name");

			Query queryObject = session.createSQLQuery(sb.toString());
			queryObject.setLong(0, pm.getUserId());
			List<ParkOrder> list = queryObject.list();
			return list;
		} catch (RuntimeException re) {
			re.getStackTrace();
			log.error("find all failed", re);
			throw re;
		}
	}

	public ParkOrder queryDaynum(ParkOrder object, UserBean userBean) {
		log.debug("finding all ParkOrder instances");
		try {
			session = this.getSession();
			ParkManager pm = (ParkManager) session.get(ParkManager.class,
					userBean.getId());
			if (pm == null)
				return null;
			String queryString = "select DATE_FORMAT((leaveTime),'%Y-%m-%d') from ParkOrder where parkinfo.PId in( select PId from ParkinfoManagerRelevance where userId=?)" +
					" group by DATE_FORMAT((leaveTime),'%Y-%m-%d')";
			getSession().createQuery(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
		return object;
	}
	//from park_order p,parkinfo pi where pi.p_id in(SELECT p_id from parkinfo_manager_relevance WHERE user_id=?) and pi.p_id=p.p_id  group by status;
	public List getstatus() {
		log.debug("finding all ParkOrder instances");
		try {
			String queryString = "from ParkOrder  group by status";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
}